package com.ly.sms.utils;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.FileAppender;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.LoggerFactory;

/**
 * @author liyong
 * @version 2020年2月14日
 */
public class LoggerBuilder {

    private static final Map<String, Logger> container = new HashMap<>();

    private static Logger build(String path, String name) {
        FileAppender debugAppender = new BatjobLoggerAppender().getAppender(path, name);
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger logger = context.getLogger("FILE-" + name);
        // 设置向上级打印信息
        logger.setAdditive(true);
        logger.addAppender(debugAppender);
        logger.setLevel(Level.DEBUG);

        return logger;
    }

    public Logger getLogger(String path, String name) {
        Logger logger = container.get(name);
        if (logger != null) {
            return logger;
        }
        synchronized (LoggerBuilder.class) {
            logger = container.get(name);
            if (logger != null) {
                return logger;
            }
            logger = build(path, name);
            container.put(name, logger);
        }
        return logger;
    }
}
